package myzzyl.utils;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import myzzyl.domain.dto.MemberLoginDto;
import myzzyl.domain.vo.MemberLoginVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class WxServiceUtil {

    private static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private static final String GTE_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";


    @Value("${zzyl.wx.appid}")
    private String appId;

    @Value("${zzyl.wx.secret}")
    private String secret;


    // 登录方法
    public String login(String code) {
        // 获取基础的appid和secret
        Map<String, Object> map = getConfig();
        // 添加额外参数
        map.put("js_code", code);

        // 调用微信登录接口
        String result = HttpRequest.get(LOGIN_URL)
                .form(map)
                .timeout(3000)
                .execute().body();

        // 解析返回的json格式字符串
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 处理错误情况
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode")) && jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }else {
            return jsonObject.getStr("openid");
        }
    }

    // 获取手机号方法
    public String getPhone(String phoneCode) {
        // 先获取token
        String accessToken = getAccessToken();
        // 拼接url
        String url = GTE_PHONE_URL + accessToken;

        // 添加额外参数
        Map<String, Object> map = new HashMap<>();
        map.put("code", phoneCode);

        // 发送请求
        String result = HttpRequest.post(url)
                .body(JSONUtil.toJsonStr(map))
                .contentType("application/json")
                .timeout(3000)
                .execute().body();
        // 解析返回的json格式字符串
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 处理错误情况
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode")) && jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }else {
            return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        }

    }


    // 获取AccessToken
    private String getAccessToken() {
        Map<String, Object> map = getConfig();

        String result = HttpRequest.get(GET_TOKEN_URL)
                .form(map)
                .timeout(3000)
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 处理错误情况
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode")) && jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }else {
            return jsonObject.getStr("access_token");
        }
    }


    // 获取基础请求参数
    private Map<String, Object> getConfig() {
        Map<String, Object> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        return map;
    }


}
